//
//  ZCullingDetailViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/24.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZCullingDetailViewController.h"

#import "ZCullingDetailCollectionViewCell.h"
#import "ZCullingAddCollectionViewCell.h"

static NSString * const ZCullingDetailCollectionViewIdentifier = @"ZCullingDetailCollectionViewIdentifier";

static NSString * const ZCullingAddCollectionViewCellIdentifier = @"ZCullingAddCollectionViewCellIdentifier";
#import "JTTakeAlbumOrCamera.h"
@interface ZCullingDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate> {
    UICollectionView * _zCDCollectionView;
    UIButton * _defineBtn;
    NSMutableArray  <UIImage *> * _imageArray;
}
@end

@implementation ZCullingDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
}

- (void)initialzeDatas {
    _imageArray = [NSMutableArray array];
}

- (void)initlizeInterface {
    self.navigationItem.title = @"已上传";
    self.view.backgroundColor = [UIColor whiteColor];
    _defineBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_defineBtn setBackgroundColor:MYGREENColor];
    [_defineBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_defineBtn setTintColor:[UIColor whiteColor]];
    [_defineBtn addTarget:self action:@selector(defineBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    UICollectionViewFlowLayout * homeLayout=[[UICollectionViewFlowLayout alloc] init];
    homeLayout.minimumLineSpacing = 5;
    homeLayout.itemSize = CGSizeMake(95 *xsIZE,95*ysIZE);
    homeLayout.sectionInset = UIEdgeInsetsMake(5*xsIZE, 5*xsIZE, 5*xsIZE, 5*xsIZE);
    _zCDCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, 400*ysIZE) collectionViewLayout:homeLayout];
    _zCDCollectionView.backgroundColor = KHColorFromRGB(0xf8f8f8f8);
    _zCDCollectionView.showsVerticalScrollIndicator = YES;
    _zCDCollectionView.delegate = self;
    _zCDCollectionView.dataSource = self;
    
    [_zCDCollectionView registerClass:[ZCullingDetailCollectionViewCell class] forCellWithReuseIdentifier:ZCullingDetailCollectionViewIdentifier];
    [_zCDCollectionView registerClass:[ZCullingAddCollectionViewCell class] forCellWithReuseIdentifier:ZCullingAddCollectionViewCellIdentifier];
    [self.view addSubview: _zCDCollectionView];
    [self.view addSubview:_defineBtn];
    [_zCDCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.width.equalTo(self.view);
        make.height.offset(500*ysIZE);
    }];
    [_defineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.width.equalTo(self.view);
        make.height.offset(50*ysIZE);
    }];
    
}


// 确定按钮点击
- (void)defineBtnAction {
    _defineBtn.userInteractionEnabled = NO;
    NSDictionary *paramas = @{@"id":_artID,@"uid":_uid,@"type":_type};
    NSMutableDictionary *fileDict = [NSMutableDictionary dictionary];
    for (int i = 0; i < _imageArray.count; i++ ) {
        [fileDict setObject:_imageArray[i] forKey:[NSString stringWithFormat:@"pic-%d",i]];
    }
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD showProgress:@"上传中..." inView:self.view];
    [BaseRequest requestWithMethodForFile:TestURL paramars:paramas paramarsSite:@"File/upImgs" fileDict:fileDict progressBlock:nil successBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"-------上传照片数据--------%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"上传成功" inView:self.view];
            _defineBtn.userInteractionEnabled = YES;
            [weakSelf back];
        }else if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"上传失败" inView:self.view];
        }
    } failure:^(NSError * error) {
        LZLog(@"---上传照片错误数据----%@",error);
    }];
}


// 集合视图协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (_imageArray.count == 0 || _imageArray.count <8) {
        return _imageArray.count+1;
    }else {
        return 9;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_imageArray.count == 0 ) {
        ZCullingAddCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZCullingAddCollectionViewCellIdentifier forIndexPath:indexPath];
        return cell;
    }else if (_imageArray.count <9 && indexPath.row == _imageArray.count) {
        ZCullingAddCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZCullingAddCollectionViewCellIdentifier forIndexPath:indexPath];
        return cell;
    }
    ZCullingDetailCollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:ZCullingDetailCollectionViewIdentifier forIndexPath:indexPath];
    cell.CDCImageView.image = _imageArray[indexPath.row ];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _imageArray.count ) {
        [JTTakeAlbumOrCamera takeAlbumWithViewcontroller:self withID:self];
    }
    return;
}

// 照片回调协议
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [_imageArray insertObject:image atIndex:_imageArray.count];
    [_zCDCollectionView reloadData];
}


// 上传成功以后刷新返回
- (void)back {
    // 判断代理是否存在
    if (self.delegate && [self.delegate conformsToProtocol:@protocol(ZCullingDetailViewControllerDelegate)]) {
        [self.delegate refreshWithType:_type];
    }
    
    // 延迟一秒返回
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
